import { createVNode, render } from 'vue';
import Toast from '../components/common/Toast.vue';

// 创建容器
const createContainer = () => {
  const container = document.createElement('div');
  container.className = 'toast-container-wrapper';
  document.body.appendChild(container);
  return container;
};

// 获取容器
const getContainer = () => {
  let container = document.querySelector('.toast-container-wrapper');
  if (!container) {
    container = createContainer();
  }
  return container;
};

// Toast实例列表
const instances: any[] = [];
let seed = 1;

// 关闭单个Toast
const closeToast = (id: string) => {
  const index = instances.findIndex(instance => instance.id === id);
  if (index === -1) return;
  
  const instance = instances[index];
  if (!instance) return;
  
  instances.splice(index, 1);
  
  // 移除DOM
  const container = getContainer();
  if (container && instance.container) {
    container.removeChild(instance.container);
  }
};

// 创建Toast
const showToast = (options: {
  message: string;
  type?: 'success' | 'error' | 'warning' | 'info';
  duration?: number;
}) => {
  const id = `toast_${seed++}`;
  const container = document.createElement('div');
  container.id = id;
  
  // 默认配置
  const defaultOptions = {
    message: '',
    type: 'info',
    duration: 3000,
    visible: true,
    onClose: () => closeToast(id)
  };
  
  // 合并配置
  const props = {
    ...defaultOptions,
    ...options
  };
  
  // 创建虚拟节点
  const vnode = createVNode(Toast, props);
  
  // 渲染到容器
  render(vnode, container);
  
  // 添加到body
  getContainer().appendChild(container);
  
  // 保存实例
  const instance = {
    id,
    vnode,
    container,
    close: () => {
      // 设置visible为false触发动画
      vnode.component!.props.visible = false;
      
      // 延迟移除DOM，等待动画完成
      setTimeout(() => {
        closeToast(id);
      }, 300);
    }
  };
  
  instances.push(instance);
  
  return instance;
};

// 导出不同类型的Toast方法
export const ToastService = {
  info: (message: string, duration = 3000) => showToast({ message, type: 'info', duration }),
  success: (message: string, duration = 3000) => showToast({ message, type: 'success', duration }),
  warning: (message: string, duration = 3000) => showToast({ message, type: 'warning', duration }),
  error: (message: string, duration = 3000) => showToast({ message, type: 'error', duration }),
  closeAll: () => {
    instances.forEach(instance => instance.close());
  }
};

export default ToastService;